#include "visualsystem.h"
#include <QDir>
#include "../../Camera/camera.h"
#include "visualrecognition.h"

#include "component_log.h"

VisualSystem::VisualSystem(QObject* parent)
	: QObject(parent)
{

}

VisualSystem::~VisualSystem()
{}


bool VisualSystem::Init(const VisualInfo& info)
{
	m_id = info.id;
	if (m_id.isEmpty()) {
		log_error("visual id is empty");
		return false;
	}
	m_camera = Camera::GetCameraDevice(info.brand);
	if (m_camera == nullptr) {
		log_error("camera bran is error, {}", info.brand);
		return false;
	}
	CameraParam param = {};
	param.id = m_id;
	param.ip = info.ip;
	param.path = info.path;
	int ret = m_camera->CameraInit(param);
	if (ret != 0) {
		log_error("camera {} init failed", param.id);
		return false;
	}
	if (!CreatePicturePath(info.path, info.ip)) {
		log_error("path create failed");
		return false;
	}
	m_recog = new VisualRecognition();
	VisRecogParam pa = {};
	pa.path = info.visPath;
	if (!m_recog->Init(pa)) {
		log_error("vis recog init  failed");
		return false;
	}
	return true;
}

bool VisualSystem::StartSnap(int index)
{
	if (index <= 0) {
		m_task++;
		log_trace("Start Maual snap index [{}]", m_task);
		return m_camera->StartSnap(m_task);
	}
	log_trace("start snap index [{}]", index);
	return m_camera->StartSnap(index);
}

VisualResult VisualSystem::GetResult(int index)
{
	while (m_result.size() > 0) {
		auto iter = m_result.dequeue();
		if (iter.first == index) {
			return iter.second;
		}
	}
	log_error("Not find visua result, index = {}", index);
	return {};
}


void VisualSystem::OnCameraSnapfinish(int index)
{
	auto result = m_camera->GetSnapResult(index);
	if (result.size() != 2) {
		log_error("reciver bad result");
		return;
	}
	if (index == m_task) {
		emit VisualSelfFinished(result.at(0));
	}
	VisualResult temp = {};
	temp.index = index;
	temp.rgb = result.at(0);
	temp.depth = result.at(1);
	int num = m_recog->GetRecognitionResult(temp.rgb, temp.rect);
	if (num > 0) {
		log_trace("visual result index {} recog finish", index);
		temp.valied = true;
	} else if (num < 0) {
		temp.valied = false;
		log_error("视觉识别服务通信出错");
	} else {	// 未识别箱子，重新识别
		num = m_recog->GetRecognitionResult(temp.rgb, temp.rect);
		if (num >= 0) {
			temp.valied = true;
		} else {
			temp.valied = false;
			log_error("视觉识别服务通信出错");
		}
	}

	m_result.enqueue(QPair(index, temp));
}


bool VisualSystem::CreatePicturePath(const QString& path, const QString& ip)
{
	QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd");
	m_savePath = path + '/' + ip + '/' + time + '/';
	QDir dir;
	if (!dir.exists(m_savePath)) {
		bool ret = dir.mkdir(m_savePath);
		if (ret) {
			log_trace("camera parh [{}] create successed", m_savePath);
			return true;
		} else {
			log_trace("camera parh [{}] create failed", m_savePath);
			return false;
		}
	}

	return true;
}
